﻿using GetMan.Core.DB.Entities;
using System.Collections.Generic;
using System.ComponentModel.Composition;

namespace GetMan.Core.DB.Services
{
    public class BaseService<TEntity> : IBaseService<TEntity, long> where TEntity : Entity
    {
        protected readonly IFreeSql _freeSql;

        [ImportingConstructor]
        public BaseService(IFreeSql freeSql)
        {
            _freeSql = freeSql;
        }

        public virtual long Add(TEntity entity)
        {
            return _freeSql.Insert(entity)
                .ExecuteIdentity();
        }

        public virtual int Update(TEntity entity)
        {
            return _freeSql.Update<TEntity>()
                .SetSource(entity)
                .ExecuteAffrows();
        }

        public virtual int Delete(long id)
        {
            return _freeSql.Delete<TEntity>(id).ExecuteAffrows();
        }

        public virtual TEntity Get(long id)
        {
            return _freeSql.Select<TEntity>().Where(x => x.Id == id).First();
        }

        public virtual List<TEntity> GetAll()
        {
            return _freeSql.Select<TEntity>().OrderBy(x => x.Id).ToList();
        }
    }
}